<?php
class Database {
    private static $instance = null;
    private $connection;
    
    private function __construct() {
        $config = require_once __DIR__ . '/../config/database.php';
        
        try {
            // 尝试直接连接到数据库
            $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']};charset={$config['charset']}";
            $this->connection = new PDO(
                $dsn,
                $config['username'],
                $config['password'],
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
        } catch (PDOException $e) {
            // 如果连接失败，检查是否是因为数据库不存在
            if (strpos($e->getMessage(), 'Unknown database') !== false || 
                strpos($e->getMessage(), 'Access denied') !== false) {
                
                // 尝试不指定数据库名称连接
                try {
                    $baseDsn = "mysql:host={$config['host']};port={$config['port']}";
                    $tempConnection = new PDO(
                        $baseDsn,
                        $config['username'],
                        $config['password'],
                        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                    );
                    
                    // 创建数据库
                    $tempConnection->exec("CREATE DATABASE IF NOT EXISTS `{$config['database']}` 
                                          DEFAULT CHARACTER SET {$config['charset']} 
                                          COLLATE {$config['charset']}_unicode_ci");
                    
                    // 现在可以连接到新创建的数据库
                    $this->connection = new PDO(
                        $dsn,
                        $config['username'],
                        $config['password'],
                        [
                            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                            PDO::ATTR_EMULATE_PREPARES => false
                        ]
                    );
                    
                    // 提示用户访问安装页面以完成安装
                    if (!file_exists(__DIR__ . '/../.installed')) {
                        // 仅当不在安装页面时显示此消息
                        $script_name = $_SERVER['SCRIPT_NAME'] ?? '';
                        if (basename($script_name) !== 'install.php') {
                            echo "<div style='background-color: #f8d7da; color: #721c24; padding: 12px; margin: 10px 0; border-radius: 4px; border: 1px solid #f5c6cb;'>";
                            echo "数据库已自动创建，请<a href='/install.php' style='color: #721c24; text-decoration: underline;'>点击此处</a>完成系统安装。";
                            echo "</div>";
                        }
                    }
                    
                } catch (PDOException $innerException) {
                    die('数据库连接失败: ' . $innerException->getMessage() . 
                        '<br>请确保您的数据库用户名和密码正确，并且用户具有创建数据库的权限。');
                }
            } else {
                die('数据库连接失败: ' . $e->getMessage());
            }
        }
    }
    
    // 防止对象被克隆
    private function __clone() {}
    
    // 获取数据库连接实例
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance->connection;
    }
    
    // 执行SQL查询
    public static function query($sql, $params = []) {
        try {
            $stmt = self::getInstance()->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch (PDOException $e) {
            // 返回更详细的错误信息，包括SQL语句
            $errorMessage = 'SQL错误: ' . $e->getMessage() . "\n查询: " . $sql;
            if (!empty($params)) {
                $errorMessage .= "\n参数: " . print_r($params, true);
            }
            die($errorMessage);
        }
    }
    
    // 获取一行数据
    public static function fetch($sql, $params = []) {
        return self::query($sql, $params)->fetch();
    }
    
    // 获取所有数据
    public static function fetchAll($sql, $params = []) {
        return self::query($sql, $params)->fetchAll();
    }
    
    // 获取查询结果的第一列第一行的值
    public static function fetchColumn($sql, $params = []) {
        return self::query($sql, $params)->fetchColumn();
    }
    
    // 插入数据
    public static function insert($table, $data) {
        $columns = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));
        
        $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
        
        self::query($sql, array_values($data));
        return self::getInstance()->lastInsertId();
    }
    
    // 更新数据
    public static function update($table, $data, $where, $whereParams = []) {
        $setClauses = [];
        $params = [];
        
        foreach ($data as $key => $value) {
            $setClauses[] = "{$key} = ?";
            $params[] = $value;
        }
        
        $setClause = implode(', ', $setClauses);
        $params = array_merge($params, $whereParams);
        
        $sql = "UPDATE {$table} SET {$setClause} WHERE {$where}";
        
        self::query($sql, $params);
    }
    
    // 删除数据
    public static function delete($table, $where, $params = []) {
        $sql = "DELETE FROM {$table} WHERE {$where}";
        self::query($sql, $params);
    }
    
    // 获取最后插入行的ID
    public static function lastInsertId() {
        return self::getInstance()->lastInsertId();
    }
    
    // 开始事务
    public static function beginTransaction() {
        return self::getInstance()->beginTransaction();
    }
    
    // 提交事务
    public static function commit() {
        return self::getInstance()->commit();
    }
    
    // 回滚事务
    public static function rollBack() {
        return self::getInstance()->rollBack();
    }
    
    // 检查数据库连接是否可用
    public static function isConnected() {
        try {
            if (self::$instance === null) {
                self::getInstance();
            }
            
            // 执行简单查询测试连接
            $result = self::query("SELECT 1");
            return ($result !== false);
        } catch (Exception $e) {
            error_log("数据库连接检查失败: " . $e->getMessage());
            return false;
        }
    }
} 